package com.yuwei.play


import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.graphics.Color
import android.graphics.drawable.Icon
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.bumptech.glide.Glide
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.yuwei.base.RoutePath

import com.yuwei.common.event.BusEvent
import com.yuwei.common.event.LiveDataBus
import com.yuwei.database.entity.MovieEntityItem
import com.yuwei.common.mvi.BaseMviActivity
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.FavVideoEntity
import com.yuwei.image.glide.GlideImageLoader
import com.yuwei.play.adapter.CommentAdapter
import com.yuwei.play.adapter.TabAdapter
import com.yuwei.play.databinding.ActivityPlayBinding
import com.yuwei.play.entity.BulletEntity
import com.yuwei.play.entity.CommentEntity
import com.yuwei.play.fragment.CommentsFragment
import com.yuwei.play.fragment.ProfileFragment
import com.yuwei.play.mvi.PlayIntent
import com.yuwei.play.mvi.PlayViewModel
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Duration
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser


@Route(path = RoutePath.VIDEO_PLAY_DETAIL)
class PlayActivity : BaseMviActivity<ActivityPlayBinding,PlayViewModel>() {
    lateinit var tabAdapter:TabAdapter
    val commentAdapter = CommentAdapter()
    private var list = arrayListOf<Fragment>()
    private var title = arrayListOf<String>()
    private var check = true
    var text =""
    var isStarted : Boolean = false

    @Autowired(name = "movie")
    lateinit var videoEntity: MovieEntityItem

    // 弹幕数据列表
    private val bulletList = mutableListOf<BulletEntity>()
    // 是否正在循环播放弹幕
    private var isLooping = false
    // 定时器
    private val handler = Handler(Looper.getMainLooper())
    // 弹幕间隔时间(毫秒)
    private val DANMAKU_INTERVAL = 1000L
    private lateinit var favVideoEntity: List<FavVideoEntity>

    override fun successData(it: UiState.onSuccess<*>) {
        when (it.type) {
            "getVideoComment" -> {
                val data = it.data as CommentEntity
                commentAdapter.data.addAll(data)
                list.add(ProfileFragment())
                list.add(CommentsFragment())
                title.add("简介")
                title.add("评论(${commentAdapter.data.size})")
                tabAdapter = TabAdapter(supportFragmentManager,FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,list,title)
                binding.detailVideoVp.adapter = tabAdapter
                binding.detailVideoTab.setupWithViewPager(binding.detailVideoVp)
                commentAdapter.notifyDataSetChanged()
            }
            "selectByVideoId"-> {
                favVideoEntity = it.data as List<FavVideoEntity>
                if (favVideoEntity.isEmpty()) {
                    vm.sendIntent(PlayIntent.insertFav(FavVideoEntity(videoEntity.id, false, videoEntity.title,videoEntity.description,videoEntity.videopath, videoEntity.name, videoEntity.avatar_url,videoEntity.videomainimag)))
                    vm.sendIntent(PlayIntent.selecteByVideoId(videoEntity.id))
                } else {
                    if(favVideoEntity[0].is_love){
                        GlideImageLoader.loadResImage(
                            this,
                            R.drawable.ic_love_24,
                            binding.detailVideoLove
                        )
                    }else{
                        GlideImageLoader.loadResImage(
                            this,
                            R.drawable.ic_love_25,
                            binding.detailVideoLove
                        )
                    }

                }
            }
        }

    }

    override fun failureData(error: String) {

    }

    override fun initView() {

        ARouter.getInstance().inject(this)
        SPUtils.getInstance().put("title", videoEntity.intro)
        vm.sendIntent(PlayIntent.selecteByVideoId(videoEntity.id))
        //标题
        binding.detailVideoTitle.text =  videoEntity.description
        //返回
        binding.detailVideoBack.setOnClickListener {
            finish()
        }

        binding.detailPlayer.setUp(videoEntity.videopath,false, null)
        //视频播放
        binding.detailPlayer.startPlayLogic()
        binding.detailPlayer.backButton.visibility = View.GONE
        //头像
        Glide.with(this).load( videoEntity.avatar_url).circleCrop().into(binding.detailVideoHeard)
        //用户名
        binding.detailVideoAuthor.text =  videoEntity.title
        //tab(简介，评论)
        vm.sendIntent(PlayIntent.getVideoComment(0, "7046705001120399908"))
        binding.detailVideoShareDesc.setOnClickListener {
            val web: UMWeb = UMWeb(videoEntity.videopath)
            web.title =videoEntity.title //标题
            web.setThumb(UMImage(this,videoEntity.videomainimag)) //缩略图
            web.description = videoEntity.name //描述
            ShareAction(this)
                .withMedia(web)
                .open()
        }
        binding.detailVideoGiftDesc.setOnClickListener {
            check = !check
            if (check){
                binding.detailVideoGift.setImageIcon(Icon.createWithResource(this,R.drawable.gift))
                binding.detailVideoGiftDesc.setTextColor(Color.GRAY)
            }else{
                binding.detailVideoGift.setImageIcon(Icon.createWithResource(this,R.drawable.gift_color))
                binding.detailVideoGiftDesc.setTextColor(Color.parseColor("#FF2442"))
                binding.giftDh.setAnimation(R.raw.gift); // 无需写扩展名 .json
                binding.giftDh.visibility = View.VISIBLE
                binding.giftDh.playAnimation()
            }
        }


        binding.giftDh.addAnimatorListener(object :AnimatorListener{
            override fun onAnimationStart(p0: Animator) {

            }

            override fun onAnimationEnd(p0: Animator) {
                binding.giftDh.visibility = View.GONE
                binding.giftDh.pauseAnimation()
            }

            override fun onAnimationCancel(p0: Animator) {

            }

            override fun onAnimationRepeat(p0: Animator) {

            }

        })
        //最大行数
        binding.detailVideoDanma.enableDanmakuDrawingCache(false)
        binding.detailVideoDanma.clear()
        binding.detailVideoDanma.removeAllDanmakus(true)
        val danmakuContext = DanmakuContext.create()
        binding.detailVideoDanma.prepare(object : BaseDanmakuParser() {
            override fun parse(): IDanmakus = Danmakus()
        }, danmakuContext)


        binding.linearLayout.setOnClickListener {
            val danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
                text = "dddddd";
                //设置相应的边距，这个设置的是四周的边距
                padding = 5;
                // 可能会被各种过滤器过滤并隐藏显示，若果是本机发送的弹幕，建议设置成1；
                //priority = 0;
                //设置文字大小
                textSize = 16f;
                //设置文字颜色
                textColor = Color.WHITE;
                //设置阴影的颜色
//                    textShadowColor = Color.WHITE;
                //设置线颜色
//                    underlineColor = Color.WHITE;
                //设置背景颜色
                borderColor = Color.WHITE;
                duration = Duration(5000)
                time = binding.detailVideoDanma.currentTime
            }
            //添加这条弹幕，也就相当于发送
            binding.detailVideoDanma.addDanmaku(danmaku);
            if (!isStarted) {
                binding.detailVideoDanma.start()
                isStarted = true
            }
        }
        binding.detailVideoLove.setOnClickListener {
            LiveDataBus.getDefault<BusEvent>("fav").value = BusEvent("喜欢",1)
            if(favVideoEntity[0].is_love){
                favVideoEntity[0].is_love = false
                vm.sendIntent(PlayIntent.updateFav(favVideoEntity[0]))
                GlideImageLoader.loadResImage(
                    this,
                    R.drawable.ic_love_24,
                    binding.detailVideoLove
                )
            }else{
                favVideoEntity[0].is_love = true
                vm.sendIntent(PlayIntent.updateFav(favVideoEntity[0]))
                GlideImageLoader.loadResImage(
                    this,
                    R.drawable.ic_love_25,
                    binding.detailVideoLove
                )
            }
        }

    }
    //接受数据的方法
    fun receiveBulletData(data:List<BulletEntity>){
        bulletList.clear()
        bulletList.addAll(data)
        //如果还没有开始循环，启动循环
        if (!isLooping){
            startDanmakuLoop()
        }
    }
    //开始循环播放弹幕
    private fun startDanmakuLoop(){
        isLooping = true
        var index = 0
        handler.post(object :Runnable{
            override fun run() {
                if (bulletList.isNotEmpty()  &&  binding.detailVideoDanma.isShown){
                    //获取当前的弹幕
                    val data = bulletList[index]
//                    addDanmaku(data)
                    //更新索引，继续播放
                    index = (index + 1) % bulletList.size
                }
                //继续下一个弹幕
                handler.postDelayed(this,DANMAKU_INTERVAL)
            }

        })
    }
    override fun initData() {
    }
    override fun onPause() {
        super.onPause()
        binding.detailVideoDanma.pause()
        binding.detailPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        binding.detailPlayer.onVideoResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.detailVideoDanma.release()
        binding.detailPlayer.release()
        isLooping = false
        handler.removeCallbacksAndMessages(null)
    }

}